package com.taxshare.purchaser.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.purchaser.constant.CodeConstant;
import com.taxshare.purchaser.constant.ResultConstant;
import com.taxshare.purchaser.entity.ElectronicledgerEntity;
import com.taxshare.purchaser.mapper.ElectronicledgerMapper;
import com.taxshare.purchaser.view.dto.ElectronicLedgerDTO;
import com.taxshare.purchaser.view.dto.InvoiceAuthCollectExcelDTO;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: InvoiceAuthCollectService
 * @Description:
 * @author: luozhongyi
 * @date: 2021/4/13 9:54
 */
@Slf4j
@Service
@Transactional
public class InvoiceAuthCollectService extends ServiceImpl<ElectronicledgerMapper, ElectronicledgerEntity> {

    /**
     * 修改有效税额
     *
     * @param dto
     * @return
     */
    public Response modifyValidTax(ElectronicLedgerDTO dto) {
        ElectronicledgerEntity entity = new ElectronicledgerEntity();
        entity.setInvoiceId(dto.getUuid());
        entity.setValidTax(new BigDecimal(dto.getValidTax()));
        baseMapper.updateById(entity);
        return Response.success();
    }

    /**
     * 提交至待认证
     *
     * @param dto
     * @return
     */
    public Response cancel(ElectronicLedgerDTO dto) {
        UpdateWrapper<ElectronicledgerEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.in("invoice_id", dto.getUuids());
        ElectronicledgerEntity entity = new ElectronicledgerEntity();
        entity.setSubmitState(CodeConstant.COMM_CODE_2);
        baseMapper.update(entity, updateWrapper);
        return Response.success();
    }

    /**
     * 导入提交
     *
     * @param excelFile
     * @return
     */
    public Response excelImport(MultipartFile excelFile) {
        List<InvoiceAuthCollectExcelDTO> excelDTOList;
        try {
            excelDTOList = ExcelUtil.readExcel(excelFile.getInputStream(), new InvoiceAuthCollectExcelDTO(), InvoiceAuthCollectExcelDTO.class);
        } catch (IOException e) {
            log.error("上传文件异常：", e);
            return Response.error(ResultConstant.RET_P0011_CODE, ResultConstant.RET_P0011_MSG);
        }
        //循环校验
        ElectronicledgerEntity entity;
        for (InvoiceAuthCollectExcelDTO dto : excelDTOList) {
            //判断发票是否存在
            entity = invoiceExists(dto);
            if (entity == null) {
                return Response.error(ResultConstant.RET_P0009_CODE,
                        MessageFormat.format(ResultConstant.RET_P0009_MSG, dto.getInvoiceCode(), dto.getInvoiceNo()));
            }
            //判断发票是否已经提交过
            if ("1".equals(entity.getSubmitState())) {
                return Response.error(ResultConstant.RET_P0010_CODE,
                        MessageFormat.format(ResultConstant.RET_P0010_MSG, dto.getInvoiceCode(), dto.getInvoiceNo()));
            }
        }
        //更新提交信息
        for (InvoiceAuthCollectExcelDTO dto : excelDTOList) {
            updateSubmitByExcel(dto);
        }
        return Response.success();
    }


    /**
     * 手工提交
     *
     * @param dto
     * @return
     */
    public Response add(ElectronicLedgerDTO dto) {
        QueryWrapper<ElectronicledgerEntity> queryWrapper = new QueryWrapper();
        queryWrapper.in("invoice_id", dto.getUuids());
        queryWrapper.eq("submit_state", CodeConstant.COMM_CODE_1);
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return Response.error(ResultConstant.RET_P0008_CODE, ResultConstant.RET_P0008_MSG);
        }
        QueryWrapper<ElectronicledgerEntity> invoiceStateQuery = new QueryWrapper();
        invoiceStateQuery.in("invoice_id",dto.getUuids());
        invoiceStateQuery.in("invoice_state", Arrays.asList("1","2","3","4"));
        if (baseMapper.selectCount(invoiceStateQuery)>0){
            return Response.error("PUR_117");
        }
        UpdateWrapper<ElectronicledgerEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.in("invoice_id", dto.getUuids());
        ElectronicledgerEntity entity = new ElectronicledgerEntity();
        entity.setSubmitState(CodeConstant.COMM_CODE_1);
        entity.setSubmitMode(dto.getSubmitMode());
        entity.setSubmitTime(LocalDateTime.now());
        entity.setSubmitUserid(UserInfoUtil.getUserID());
        entity.setSubmitUsername(UserInfoUtil.getUserNickName());
        baseMapper.update(entity, updateWrapper);
        return Response.success();
    }

    /**
     * 发票提交判断
     *
     * @param dto
     * @return
     */
    private ElectronicledgerEntity invoiceExists(InvoiceAuthCollectExcelDTO dto) {
        QueryWrapper<ElectronicledgerEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("invoice_code", dto.getInvoiceCode());
        queryWrapper.eq("invoice_no", dto.getInvoiceNo());
        ElectronicledgerEntity entity = baseMapper.selectOne(queryWrapper);
        return entity;
    }

    /**
     * 更新体提交信息
     *
     * @param dto
     */
    private void updateSubmitByExcel(InvoiceAuthCollectExcelDTO dto) {
        UpdateWrapper<ElectronicledgerEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("invoice_code", dto.getInvoiceCode());
        updateWrapper.eq("invoice_no", dto.getInvoiceNo());
        ElectronicledgerEntity entity = new ElectronicledgerEntity();
        entity.setSubmitState(CodeConstant.COMM_CODE_0);
        entity.setSubmitMode(CodeConstant.COMM_CODE_1);
        entity.setSubmitTime(LocalDateTime.now());
        entity.setSubmitUserid(UserInfoUtil.getUserID());
        entity.setSubmitUsername(UserInfoUtil.getUserNickName());
        baseMapper.update(entity, updateWrapper);
    }
}
